import unittest
import json
from .http_client import HttpClient
from config import BASE_URL, API_VERSION, TEST_USER, ADMIN_USER, SUCCESS_CODE

class BaseTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        """类级别的前置操作"""
        cls.base_url = f"{BASE_URL}{API_VERSION}"
        cls.client = HttpClient()
        cls普通用户token = None
        cls管理员token = None

        # 获取普通用户token
        cls.普通用户token = cls._get_token(TEST_USER)
        # 获取管理员token
        cls.管理员token = cls._get_token(ADMIN_USER)

    def setUp(self):
        """测试方法前置操作"""
        # 普通用户默认 headers
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.普通用户token}" if self.普通用户token else ""
        }
        # 管理员 headers
        self.admin_headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.管理员token}" if self.管理员token else ""
        }

    @classmethod
    def _get_token(cls, user_info):
        """获取登录token"""
        if not user_info:
            return None
            
        url = f"{cls.base_url}/user/login"
        try:
            response = cls.client.post(
                url=url,
                json=user_info
            )
            result = response.json()
            if result.get("code") == SUCCESS_CODE:
                return result.get("data", {}).get("token")
            return None
        except Exception as e:
            print(f"获取token失败: {str(e)}")
            return None

    def assert_response(self, response, expected_code=SUCCESS_CODE):
        """通用响应断言"""
        # 断言状态码
        self.assertEqual(response.status_code, 200)
        
        # 解析响应
        try:
            result = response.json()
        except json.JSONDecodeError:
            self.fail("响应不是有效的JSON格式")
            
        # 断言业务状态码
        self.assertEqual(result.get("code"), expected_code, 
                       f"业务状态码错误: {result.get('code')}, 消息: {result.get('message')}")
        
        return result